package patrol.mobile.com.mobilepatrol.activity.monitor;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.office.AdviceDetailActivity;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.bean.DateBean;
import patrol.mobile.com.mobilepatrol.bean.MingxiMoBanBean;
import patrol.mobile.com.mobilepatrol.utils.DatePickerUtil02;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.TimeUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.view.CallBack;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

public class XjMingXiMuDetailActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.titleText)
    TextView titleText;
//    @BindView(R.id.isOkText)
//    TextView isOkText;
//    @BindView(R.id.isOkImage)
//    ImageView isOkImage;
//    @BindView(R.id.isBadText)
//    TextView isBadText;
//    @BindView(R.id.isBadImage)
//    ImageView isBadImage;
    @BindView(R.id.gzqkEdit)
    EditText gzqkEdit;
    @BindView(R.id.wxjlEdit)
    EditText wxjlEdit;
    @BindView(R.id.whjlEdit)
    EditText whjlEdit;
    @BindView(R.id.wxjlsjEdit)
    TextView wxjlsjEdit;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.commitText)
    TextView commitText;
    @BindView(R.id.upPageText)
    TextView upPageText;
    @BindView(R.id.downPageText)
    TextView downPageText;
    @BindView(R.id.isOkText)
    RadioButton radioButtonOk;
    @BindView(R.id.isBadText)
    RadioButton radioButtonBad;
    MingxiMoBanBean mingxiMoBanBean;
    private List<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    private int limitSize = 4;
    private int position;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_deltail_xj_mingxi_layout;
    }


    @Override
    public void initData() {
        super.initData();
        mingxiMoBanBean = (MingxiMoBanBean) getIntent().getSerializableExtra("data");
        position = getIntent().getIntExtra("position", 0);
        iv_back.setVisibility(View.VISIBLE);
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("巡检记录编辑");
        wxjlsjEdit.setText(TimeUtils.timeString(System.currentTimeMillis()));
        wxjlsjEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerUtil02.getInstance(v.getContext()).setCallBack(new CallBack<DateBean>() {
                    @Override
                    public void onBack(DateBean dateBean) {
                        wxjlsjEdit.setText(dateBean.getmDate());
                    }
                });
            }
        });
        setData();
    }

    private void setData() {
        titleText.setText(mingxiMoBanBean.getList().get(position).getPosition() + "  " + mingxiMoBanBean.getList().get(position).getEquipmentName());
        gzqkEdit.setText(mingxiMoBanBean.getList().get(position).getFaultSituation());
        wxjlEdit.setText(mingxiMoBanBean.getList().get(position).getMaintenanceLog());
        whjlEdit.setText(mingxiMoBanBean.getList().get(position).getMaintenanceRecord());
        selImageList = mingxiMoBanBean.getList().get(position).getImages();
        setIsOk();
        initImagePicker();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private void setIsOk() {
        if (mingxiMoBanBean.getList().get(position).getEquipmentStatus().equals("0")) {
            radioButtonOk.setChecked(true);
            radioButtonBad.setChecked(false);
//            isOkImage.setImageResource(R.mipmap.danxuan_ok);
//            isBadImage.setImageResource(R.mipmap.danxuan);
        } else {
            radioButtonOk.setChecked(false);
            radioButtonBad.setChecked(true);
        }
    }

    @Override
    public void setListener() {
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("data", mingxiMoBanBean);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
        radioButtonOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mingxiMoBanBean.getList().get(position).setEquipmentStatus("0");
                setIsOk();
            }
        });
        radioButtonBad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mingxiMoBanBean.getList().get(position).setEquipmentStatus("1");
                setIsOk();
            }
        });
        upPageText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                saveData();
                if (position == 0) {
                    ToastUtils.showToast("已经是第一页了");
                    return;
                }
                position--;
                setData();
            }
        });
        downPageText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveData();
                if (position >= mingxiMoBanBean.getList().size()) {
                    ToastUtils.showToast("已经是最后一页了");
                    return;
                }
                position++;
                setData();
            }
        });
//        commitText.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mingxiMoBanBean.getList().get(position).setFaultSituation(gzqkEdit.getText().toString());
//                mingxiMoBanBean.getList().get(position).setMaintenanceLog(wxjlEdit.getText().toString());
//                mingxiMoBanBean.getList().get(position).setMaintenanceRecord(whjlEdit.getText().toString());
//                mingxiMoBanBean.getList().get(position).setImages(selImageList);
//                ToastUtils.showToast("数据保存成功");
//            }
//        });

    }

    private void saveData() {
        mingxiMoBanBean.getList().get(position).setFaultSituation(gzqkEdit.getText().toString());
        mingxiMoBanBean.getList().get(position).setMaintenanceLog(wxjlEdit.getText().toString());
        mingxiMoBanBean.getList().get(position).setMaintenanceRecord(whjlEdit.getText().toString());
        mingxiMoBanBean.getList().get(position).setImages(selImageList);
        ToastUtils.showToast("数据保存成功");
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("data", mingxiMoBanBean);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case AdviceDetailActivity.IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(view.getContext(), ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(view.getContext(), ImageGridActivity.class);
                                startActivityForResult(intent1, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, AdviceDetailActivity.REQUEST_CODE_PREVIEW);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    ArrayList<ImageItem> images;
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
            }
        }
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }
}
